package com.mk.filter;

import com.mk.properties.JwtProperties;
import com.mk.service.impl.UserServiceImpl;
import com.mk.utils.JwtUtil;
import jakarta.annotation.PostConstruct;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * 自定义过滤器
 */
@Component
@RequiredArgsConstructor
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    private final UserServiceImpl userService;

    @Resource
    private JwtProperties jwtProperties;

    private final JwtUtil jwtUtil;

//    //延迟初始化JwtUtil
//    @PostConstruct
//    public void init() {
//        this.jwtUtil = new JwtUtil(jwtProperties.getUserSecretKey());
//    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        // 读取请求头中的token
        String requestToken = request.getHeader(jwtProperties.getTokenName());
        if (StringUtils.isNotBlank(requestToken)) {
            // 解析token中的用户信息（用户名）
            String username = jwtUtil.extractUsername(requestToken);

            // 判断token是否有效
            boolean verifyToken = jwtUtil.validateToken(requestToken, username);
            if (!verifyToken) {
                filterChain.doFilter(request, response);
            }

            if (StringUtils.isNotBlank(username) && SecurityContextHolder.getContext().getAuthentication() == null) {

                UserDetails userDetails = userService.loadUserByUsername(username);
                // 保存用户信息到当前会话
                UsernamePasswordAuthenticationToken authentication =
                        new UsernamePasswordAuthenticationToken(
                                userDetails,
                                null,
                                userDetails.getAuthorities());
                // 将authentication填充到安全上下文
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        filterChain.doFilter(request, response);

    }
}
